package it.eng.area118.mdocommon.log;

import java.util.Date;

/**
 * 
 * Uitlity class for obtnain
 * 
 */
public class Logger {

	public final static int CONSOLE = 2;

	public final static int FILE = 1;

	private static Log INSTANCE;

	private static String fileName;
	private static int numOldLogs;

	private static String logLevel = "";

	private static int logType = -1;

	private static void createLog(int logType, String level, Class clazz) {
		switch (logType) {
		case 1:
			INSTANCE = new DailyFileLogger(fileName, level, numOldLogs);
			INSTANCE.start();
			break;
		case 2:
			INSTANCE = new ConsoleLogger(clazz);
			ConsoleLogger.setDefaultLevel(level);
			break;
		default:
			INSTANCE = new ConsoleLogger(clazz);
			ConsoleLogger.setDefaultLevel(level);
			logType = -1;
			break;
		}
		logLevel = level;
	}

	public synchronized static Log getInstance(Class clazz) {
		if (INSTANCE == null) {
			createLog(logType, logLevel, clazz);
		}
		return INSTANCE;
	}

	public static void changeLogType(int type) {
		if (logType != type) {
			if (INSTANCE != null) {
				INSTANCE.close();
			}
			createLog(type, logLevel, null);
		}
		logType = type;
	}

	public synchronized static void changeLogLevel(String level) {
		if (!logLevel.equals(level)) {
			if (INSTANCE != null) {
				INSTANCE.close();
			}
			createLog(logType, logLevel, null);
		}
		logLevel = level;
	}

	public synchronized static void init(String file, String level, int type, int oldLogs) {
		fileName = file;
		logLevel = level;
		numOldLogs = oldLogs;
		if (logType != type) {
			logType = type;
			if (INSTANCE != null) {
				INSTANCE.close();
			}
			createLog(type, level, null);
			// INSTANCE = null;
		}
	}

	public static void main(String[] args) {
		Logger.init("terminal118", "DEBUG", Logger.FILE, 10);
		Log log = Logger.getInstance(null);
		for (int i = 0; i < 100; i++) {
			System.out.println(new Date());
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// CREME Auto-generated catch block
				e.printStackTrace();
			}
			log.debug("DEADASDASDASDASD  " + i);
		}
		log.close();
	}
}
